import OrgTree from '@/components/OrgTree';
import SearchTablePage, { SearchTablePageRefType } from '@/components/SearchTablePage';
import { PERMISSION_KEY_TERMINAL_MANAGE } from '@/constants';
import { getOrgTrees } from '@/services/system/org';
import { getBrandSelect } from '@/services/terminal/brand';
import {
  addTerminal,
  deleteTerminalById,
  getTerminalById,
  getTerminalListByPage,
  updateTerminal,
} from '@/services/terminal/manage';
import { getTerminalModelSelect } from '@/services/terminal/model';
import { getTerminalTypeSelect } from '@/services/terminal/type';
import { formatOptions, optionsToValueEnum } from '@/utils/dataTransferUtils';
import { checkRespSuccessful } from '@/utils/serviceUtils';
import { useToken } from '@ant-design/pro-components';
import { useModel, useRequest } from '@umijs/max';
import { message } from 'antd';
import { Key, useRef, useState } from 'react';

const Brand: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { token } = useToken();
  const [selectOrgIdList, setSelectOrgIdList] = useState<Key[]>([]);
  const searchTablePageActionRef = useRef<SearchTablePageRefType>(null);
  const {
    data: brandSelect,
    error: getBrandSelectError,
    refresh: refreshBrandSelect,
  } = useRequest(getBrandSelect);

  if (getBrandSelectError) {
    message.error(getBrandSelectError.message);
    console.error('error', getBrandSelectError);
  }

  const {
    data: terminalModelSelect,
    error: getTerminalModelError,
    refresh: refreshTerminalModelSelect,
  } = useRequest(getTerminalModelSelect);

  if (getTerminalModelError) {
    message.error(getTerminalModelError.message);
    console.error('error', getTerminalModelError);
  }

  const {
    data: terminalTypeSelect,
    error: getTerminalTypeError,
    refresh: refreshTerminalTypeSelect,
  } = useRequest(getTerminalTypeSelect);

  if (getTerminalTypeError) {
    message.error(getTerminalTypeError.message);
    console.error('error', getTerminalTypeError);
  }
  return (
    <>
      <SearchTablePage<API.Terminal>
        tableName="设备"
        getRowById={getTerminalById}
        updateRow={updateTerminal}
        addRow={addTerminal}
        deleteRowById={deleteTerminalById}
        getRowsByPage={getTerminalListByPage}
        permissionKey={PERMISSION_KEY_TERMINAL_MANAGE}
        rowSelection={false}
        ref={searchTablePageActionRef}
        modalFormWidth={640}
        modalFormLabelCol={{ flex: '8em' }}
        grid
        params={{
          orgId: selectOrgIdList?.length > 0 ? selectOrgIdList[0] : undefined,
        }}
        onAdd={() => {
          if (selectOrgIdList.length > 0) {
            setTimeout(() => {
              searchTablePageActionRef.current?.setModalFormFieldValue('orgId', selectOrgIdList[0]);
            });
          }
        }}
        onReset={() => {
          setSelectOrgIdList([]);
        }}
        onModalFormOpen={() => {
          refreshBrandSelect();
          refreshTerminalTypeSelect();
          refreshTerminalModelSelect();
        }}
        columns={[
          {
            title: '设备 ID',
            dataIndex: 'id',
            hideInTable: true,
            hideInSearch: true,
            hideInModal: true,
          },
          {
            title: '设备编号',
            dataIndex: 'no',
            showDetail: true,
            rules: [{ required: true }],
            colProps: { span: 12 },
          },
          {
            title: '设备名称',
            dataIndex: 'name',
            rules: [{ required: true }],
            colProps: { span: 12 },
          },
          {
            title: '设备 IP',
            dataIndex: 'ip',
            rules: [{ required: true }],
            colProps: { span: 12 },
          },
          {
            title: '设备端口',
            dataIndex: 'port',
            hideInSearch: true,
            hideInTable: true,
            rules: [{ required: true }],
            colProps: { span: 12 },
          },
          {
            title: 'MAC 地址',
            dataIndex: 'mac',
            hideInSearch: true,
            hideInTable: true,
            rules: [{ required: true }],
            colProps: { span: 12 },
          },

          {
            title: '所属机构',
            dataIndex: 'orgId',
            valueType: 'treeSelect',
            allowClear: true,
            hideInSearch: true,
            colProps: { span: 12 },
            fieldProps: {
              fieldNames: {
                value: 'id',
              },
            },
            request: async () => {
              const res = await getOrgTrees();
              if (checkRespSuccessful(res)) {
                return res.data;
              }
              return [];
            },
            rules: [{ required: true, message: '请选择' }],
          },
          {
            title: '设备厂商',
            dataIndex: 'brandId',
            valueType: 'select',
            valueEnum: optionsToValueEnum(brandSelect, { label: 'name', value: 'id' }),
            options: formatOptions(brandSelect, { label: 'name', value: 'id' }),
            rules: [{ required: true }],
            colProps: { span: 12 },
          },
          {
            title: '设备类型',
            dataIndex: 'typeId',
            valueType: 'select',
            valueEnum: optionsToValueEnum(terminalTypeSelect, { label: 'cnName', value: 'id' }),
            options: formatOptions(terminalTypeSelect, { label: 'cnName', value: 'id' }),
            rules: [{ required: true }],
            colProps: { span: 12 },
          },
          {
            title: '设备型号',
            dataIndex: 'modelId',
            valueType: 'select',
            valueEnum: optionsToValueEnum(terminalModelSelect, { label: 'name', value: 'id' }),
            options: formatOptions(terminalModelSelect, { label: 'name', value: 'id' }),
            rules: [{ required: true }],
            colProps: { span: 12 },
          },
          {
            title: '启用日期',
            dataIndex: 'activeTime',
            valueType: 'dateTime',
            hideInSearch: true,
            hideInTable: true,
            rules: [{ required: true }],
            colProps: { span: 12 },
          },
          {
            title: '设备序列号',
            dataIndex: 'serialNumber',
            hideInSearch: true,
            hideInTable: true,
            rules: [{ required: true }],
            colProps: { span: 12 },
          },
          {
            title: '状态',
            dataIndex: 'status',
            valueType: 'select',
            valueEnum: initialState?.system_common_status?.valueEnum,
            options: initialState?.system_common_status?.numOptions,
            rules: [{ required: true, message: '请选择状态' }],
            colProps: { span: 12 },
          },
          {
            title: '设备地址',
            dataIndex: 'address',
            hideInSearch: true,
            hideInTable: true,
            rules: [{ required: true }],
            colProps: { span: 24 },
            labelCol: { flex: '8em' },
          },
          {
            title: '柜员号',
            dataIndex: 'teller',
            hideInSearch: true,
            hideInTable: true,
            rules: [{ required: true }],
            colProps: { span: 12 },
          },
          {
            title: '尾箱号',
            dataIndex: 'trunkNo',
            hideInSearch: true,
            hideInTable: true,
            colProps: { span: 12 },
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            hideInSearch: true,
            hideInModal: true,
          },
        ]}
        leftSide={
          <OrgTree
            selectedKeys={selectOrgIdList}
            onSelect={(selectedKeys) => {
              setSelectOrgIdList(selectedKeys);
            }}
            checkPermission={false}
            style={{
              flex: '0 0 auto',
              minWidth: 160,
              maxWidth: 260,
              overflow: 'auto',
              backgroundColor: token.colorBgContainer,
              paddingTop: token.paddingContentHorizontalLG,
              paddingBottom: token.paddingContentHorizontalLG,
              paddingLeft: token.padding,
              paddingRight: token.padding,
              borderRadius: token.borderRadius,
              borderWidth: 1,
              borderStyle: 'solid',
              borderColor: token.colorBorderSecondary,
            }}
          />
        }
      />
    </>
  );
};

export default Brand;
